package cn.xiaopengstack.domain.activity.service.quota.rule.chain;

import cn.xiaopengstack.domain.activity.model.entity.ActionRuleMatterEntity;
import cn.xiaopengstack.domain.activity.model.entity.RaffleActivityCountEntity;
import cn.xiaopengstack.domain.activity.model.entity.RaffleActivitySkuEntity;
import cn.xiaopengstack.domain.activity.repository.IRaffleActivityRepository;
import cn.xiaopengstack.domain.activity.service.quota.rule.factory.DefaultActivityActionChainFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author jiangyangang
 * 库存检查
 */
@Component
@Slf4j
public class StockCheckActionChain extends AbstractActionChain{


    @Resource
    private IRaffleActivityRepository activityRepository;

    @Override
    public DefaultActivityActionChainFactory.ActionEnum action() {
        return DefaultActivityActionChainFactory.ActionEnum.STOCK_CHECK_ACTION;
    }

    @Override
    public boolean doChain(ActionRuleMatterEntity ruleMatter) {
        Integer decrNumber = ruleMatter.getDecrNumber();
        // 查询SKU库存缓存
        Integer skuStockCache = activityRepository.queryActivitySkuStockCache(ruleMatter.getActivitySku().getSku());
        if (decrNumber > skuStockCache) {
            log.warn("活动责任链, 活动SKU库存不足; {}, {}", ruleMatter.getActivity().getActivityId(), ruleMatter.getActivitySku().getSku());
            return false;
        }

        RaffleActivityCountEntity activityCount = ruleMatter.getActivityCount();
        if (decrNumber > activityCount.getTotalCount()) {
            log.warn("活动责任链, 活动库存不足; {}", ruleMatter.getActivity().getActivityId());
            return false;
        }

        RaffleActivitySkuEntity activitySku = ruleMatter.getActivitySku();
        Integer stockCountSurplus = activitySku.getStockCountSurplus();
        if (decrNumber > stockCountSurplus) {
            log.warn("活动责任链, SKU库存不足; {}, {}", activitySku.getActivityId(), activitySku.getStockCountSurplus());
            return false;
        }

        log.info("活动责任链, SKU库存检查通过 {}, {}", activitySku.getActivityId(), activitySku.getStockCountSurplus());
        return next().doChain(ruleMatter);
    }

    @Override
    public int getOrder() {
        return action().getOrder();
    }
}
